package p.ithorns.integration.hazelcast.mqtt;

import com.hazelcast.core.HazelcastInstance;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import p.ithorns.framework.common.utils.JsonUtil;

import java.nio.charset.StandardCharsets;

/**
 * @Author: liuhaitao
 * @Date: 2022/8/17 18:27
 * @Description: 上报消息
 */
@Slf4j
//@Service
public class MqttMessageDispatcher implements IMqttMessageListener {

    @Autowired
    private HazelcastInstance hz;

    /**
     * 处理消息
     *
     * @param topic       主题
     * @param mqttMessage 消息
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        String json = new String(mqttMessage.getPayload(), StandardCharsets.UTF_8);
        // log.info("收到MQTT消息：{}", json);
        Topics.Up subTopic = Topics.matchTopic(topic);
        if (null == subTopic) {
            log.warn("未知MQTT主题:{}", topic);
            return;
        }

        BaseRaw raw = JsonUtil.fromJson(json, subTopic.getRawClass());
        if (null != raw) {
            DataHandler<BaseRaw> handler = DataHandlerContext.get(subTopic);
            if (null != handler) {
                handler.handle(raw);
            }
        }
    }

}